package saas.baseinfo.service.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import saas.baseinfo.service.global.GlobalRequestResponseBodyMethodProcessor;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author guan.xin
 * @title ResolverBeanPostProcessor
 * @description
 * @create 2022-05-25 13:54
 * @since JDK8
 */
@Component
public class ResolverBeanPostProcessor implements InitializingBean {

    @Resource
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Override
    public void afterPropertiesSet() {
        List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers();

        List<HandlerMethodReturnValueHandler> returnValueHandlersNew = new ArrayList<>();

        assert returnValueHandlers != null;

        returnValueHandlers.forEach(e -> {
            if ((e instanceof RequestResponseBodyMethodProcessor)) {
                returnValueHandlersNew.add(new GlobalRequestResponseBodyMethodProcessor(requestMappingHandlerAdapter.getMessageConverters()));
            } else {
                returnValueHandlersNew.add(e);
            }
        });

        requestMappingHandlerAdapter.setReturnValueHandlers(Collections.unmodifiableList(returnValueHandlersNew));
    }
}
